﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using PayexpDAL;
using Utilities;

namespace PayexpAddUser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void addUserButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(userNameTextBox.Text) ||
                string.IsNullOrEmpty(passwordTextBox.Text) ||
                string.IsNullOrEmpty(confirmPasswordTextBox.Text))
            {
                MessageBox.Show("Please ensure all the three fields have proper values.", "Fields empty", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (!passwordTextBox.Text.Equals(confirmPasswordTextBox.Text))
            {
                MessageBox.Show("The passwords do not match. Please type them again.", "Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                passwordTextBox.Text = string.Empty;
                confirmPasswordTextBox.Text = string.Empty; ;
                return;
            }

            byte[] passwordByteArray = ASCIIEncoding.ASCII.GetBytes(passwordTextBox.Text);
            string encodedPassword = Convert.ToBase64String(passwordByteArray);

            try
            {
                DataAccessHandler dataAccessHandler = new DataAccessHandler();
                dataAccessHandler.AddUser(userNameTextBox.Text, encodedPassword, new AlfaRomeoEntities());

                MessageBox.Show("User added successfully");

                userNameTextBox.Text = string.Empty;
                passwordTextBox.Text = string.Empty;
                confirmPasswordTextBox.Text = string.Empty;
            }
            catch (DALException dex)
            {
                MessageBox.Show(dex.Message, "User Exists",  MessageBoxButtons.OK, MessageBoxIcon.Error);
                userNameTextBox.Text = string.Empty;
                passwordTextBox.Text = string.Empty;
                confirmPasswordTextBox.Text = string.Empty;
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error adding the user. Please contact your administrator");
            }
            
        }
    }
}
